import tkinter as tk
from PIL import Image
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn import metrics
import numpy as np
import io
#pillow==9.5.0


# 加载手写数字数据集
digits = datasets.load_digits()
X = digits.data
y = digits.target

# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)

# 创建SVM分类器，并在训练集上进行训练
clf = svm.SVC(gamma=0.001)
clf.fit(X_train, y_train)

# 使用训练好的模型对测试集进行预测
y_pred = clf.predict(X_test)

# 评估模型性能
print("Accuracy:", metrics.accuracy_score(y_test, y_pred))

# 创建Tkinter应用程序窗口
window = tk.Tk()
window.title("手写数字识别")
window.geometry("400x400")

# 创建画布
canvas = tk.Canvas(window, width=200, height=200, bg="white")
canvas.pack()

# 创建清除按钮
def clear_canvas():
    canvas.delete("all")

clear_button = tk.Button(window, text="清除", command=clear_canvas)
clear_button.pack()


# 创建预测按钮
def predict_digit():

    # 将画布上的图像转换为8x8像素的灰度图像
    image = canvas.postscript(colormode='gray')
    img = Image.open(io.BytesIO(image.encode('utf-8'))).convert('L')
    img =img.resize((8, 8))
    img=np.array(img).flatten()
    img = img.astype('float32')

    img =16.0-img*16/255
    prediction = clf.predict([img])


    # 显示预测结果
    result_label.config(text="预测结果: {}".format(prediction[0]))

predict_button = tk.Button(window, text="预测", command=predict_digit)
predict_button.pack()

# 创建预测结果标签
result_label = tk.Label(window, text="")
result_label.pack()

# 用于绘制数字的回调函数
def draw(event):
    x, y = event.x, event.y
    canvas.create_oval(x, y, x+10, y+10, fill="black")

canvas.bind("<B1-Motion>", draw)

# 运行Tkinter主循环
window.mainloop()